(() => {
	window.popupBlockAddBox = function (parentId, blockId) {
		if(!Core.isNumber(blockId)) {
			blockId = $(blockId).data('blockId');
		}
		
		if(PageHelper.getCurrentViewPage()) {
			let currentViewPage = PageHelper.getCurrentViewPage();
			let m = new BlockModel;
			
			if(blockId) {
				m.load(blockId);
			}
			
			layui.layer.open({
				type:1,
				btn:['确定'],
				content: Core.renderSrcFile('page/home/tools/add-block.html', {types:BlockModel.TYPE, m:m}),
				title:'添加块',
				area:['90%'],
				yes: function (index) {
					let label = $('#add_block_label').val();
					let type = $('#add_block_type').val();
					let value = $('#add_block_content').val();
					let comment = $('#add_block_comment').val();
					
					if(label == '') {
						CoreHelper.alertError('名称不能为空!');
						return;
					}

					let blockModel = new BlockModel();
					blockModel.setLabel(label)
						.setType(type)
						.setPageId(currentViewPage)
						.setValue(value)
						.setComment(comment)
						.setPosition(99999);
					
					if(parentId) {
						blockModel.setParent(parentId);
					}
					
					if(blockId) {
						blockModel.setId(blockId);
					}
					
					blockModel.save();

					if(!blockModel.ok()) {
						CoreHelper.alertError(`保存失败: ${blockModel.getError()}`);
						return false;
					}

					if(blockId) {
						BlockHelper.updateFrontendHtml(blockId, BlockHelper.render(blockModel));
					} else {
						let html = BlockHelper.render(blockModel);
						CoreHelper.getBlockElement(parentId).find('.lists').append($(html));
					}
					
					layui.layer.close(index);
					return true;
				}
			});
			
			$('#add_block_label').focus();
		}
	};
})();
